package com.lvtongka.app.ui.recharge

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.Editable
import android.text.InputFilter
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.alipay.sdk.app.PayTask
import com.androideasy.permissions.EasyPermissions
import com.androideasy.permissions.Permission
import com.icbc.ndf.jft.PayActivity
import com.icbc.ndf.jft.PayActivity.openPayActivity
import com.icbc.ndf.jft.PayNoActivity
import com.icbc.ndf.jft.contants.PayResultVO
import com.icbc.ndf.jft.utils.OrderResultCallBack
import com.icbc.ndf.jft.utils.ToastUtils
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lvtongka.app.R
import com.lvtongka.app.base.BaseActivity
import com.lvtongka.app.common.AppUtils
import com.lvtongka.app.common.CommonUtils
import com.lvtongka.app.common.FileUtils
import com.lvtongka.app.common.GlideEngine
import com.lvtongka.app.common.widget.CashierInputFilter
import com.lvtongka.app.common.widget.SpacesItemDecoration
import com.lvtongka.app.databinding.ActivityRechargeBinding
import com.lvtongka.app.fragment.common.DialogHelper
import com.lvtongka.app.fragment.common.SetPayCallback
import com.lvtongka.app.okpermission.PermissionLauncher
import com.lvtongka.app.ui.recharge.adapter.OnItemClickListener
import com.lvtongka.app.ui.recharge.adapter.RechargeAdapter
import com.lvtongka.app.ui.recharge.bean.ChannelList
import com.lvtongka.app.ui.recharge.bean.PayResult


/**
 * describe:
 * 钱包充值
 * @author:ZhangWei(张伟)
 * date:2024/11/9
 * time:16:48
 */
class RechargeActivity : BaseActivity<ActivityRechargeBinding, RechargeViewModel>() {
    companion object {
        private const val TAG = "RechargeActivity_zw_test"
        private const val SDK_PAY_FLAG: Int = 1
    }
    // 0表示谁都没选
    private var balanceChange = false
    private var selectResult = ""
    private var lvPwd = ""
    private var rechargeAdapter: RechargeAdapter? = null
    private var channelList: ChannelList?= null

    override fun onCreate(savedInstanceState: Bundle?) {
        isBlack = false
        super.onCreate(savedInstanceState)
    }

    override fun initViewModel(): RechargeViewModel {
        return ViewModelProvider(this)[RechargeViewModel::class.java]
    }

    private fun hiddenSelect() {
        binding.llLvHint.visibility = View.GONE
        binding.llLv.visibility = View.GONE
        binding.llOther.visibility = View.GONE
        binding.rvOther.visibility = View.GONE
    }

    private fun visibleSelect() {
        binding.tvSelectHint.text = "请选择支付方式"
        binding.llLvHint.visibility = View.VISIBLE
        binding.llLv.visibility = View.VISIBLE
        binding.llOther.visibility = View.VISIBLE
        binding.rvOther.visibility = View.VISIBLE

        hiddenLv()
        hiddenOther()
        selectResult = ""
    }

    private fun hiddenLv() {
        binding.rlLv.visibility = View.GONE
        binding.tvVerifyPwd.visibility = View.GONE
    }

    private fun visibleLv() {
        hiddenSelect()
        binding.tvSelectHint.text = "请输入旅通卡信息"
        binding.llLvHint.visibility = View.VISIBLE
        binding.rlLv.visibility = View.VISIBLE
        binding.tvVerifyPwd.visibility = View.VISIBLE
        selectResult = "1"
    }

    private fun hiddenOther() {
        binding.rlOther.visibility = View.GONE
        binding.tvNext.visibility = View.GONE
    }

    private fun visibleOther() {
        hiddenSelect()
        binding.rlOther.visibility = View.VISIBLE
        binding.tvNext.visibility = View.VISIBLE
        binding.etBalance.setText("")
    }

    override fun initEvent() {
        binding.rechargeHead.imgBack.setOnClickListener {
            if (TextUtils.equals(selectResult,"")) {
                if (balanceChange) {
                    setResult(RESULT_OK, Intent().putExtra("balance", binding.rechargeHead.tvQbye.text.toString()))
                }
                finish()
            } else {
                visibleSelect()
            }
        }

        binding.llLv.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            visibleLv()
        }

        binding.tvNext.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            if (binding.etBalance.text.toString().isEmpty()) {
                showToast("请输入充值金额")
                return@setOnClickListener
            }
            // 调用接口
            showLoading("请求中...")
            val je = (binding.etBalance.text.toString().toDouble() * 100).toInt()
            viewModel.rechargePay(je, channelList!!.payType)
        }
        binding.tvVerifyPwd.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            val cardNo = binding.etCardNo.text.toString()
            if (TextUtils.isEmpty(cardNo)) {
                showToast("请输入旅通卡卡号")
                return@setOnClickListener
            }
            // 验密
            DialogHelper.showPayPwdDialog(this, object : SetPayCallback {
                override fun onSetPayResult(result: String) {
                    lvPwd = result
                    showLoading("充值中...")
                    viewModel.getCardInfo(cardNo, result)
                }
            })
        }
        binding.ivTakePhoto.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            takePhotos()
        }
        viewModel.error.observe(this) {
            hideLoading()
            showToast(it)
        }
        viewModel.rechargeData.observe(this) {
            // 读取成功 开始调用充值
            viewModel.rechargeCard(
                binding.etCardNo.text.toString(), lvPwd, it.ltk_balance
            )
        }
        viewModel.rechargeCard.observe(this) {
            hideLoading()
            // 充值成功
            showToast("充值成功")
            balanceChange = true
            showLoading()
            viewModel.getMyInfo()
        }
        viewModel.rechargeAlipay.observe(this) {
            hideLoading()
            // 获取到支付信息
            when (selectResult) {
                "3"-> {
                    confirmPay(it.jumpUrl)
                }
                "6"->{
                    confirmPay(it.jumpUrl)
                }
                "4" -> {
                    getAilPay(it.jumpUrl)
                }
            }
        }
        viewModel.ocrData.observe(this) {
            hideLoading()
            binding.etCardNo.setText(it.ltk_card)
        }
        viewModel.myInfo.observe(this) {
            hideLoading()
            binding.rechargeHead.tvQbye.text = AppUtils.convertFenToYuan(it.balance)
            binding.rechargeHead.tvAccountId.text = buildString {
                append("账户ID: ")
                append(it.cell)
            }
        }
        viewModel.channelListData.observe(this) {
            hideLoading()
            it.channelList?.let {cl->
                rechargeAdapter?.setList(cl)
            }
        }
    }

    private fun takePhotos() {
        val listP = listOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
        if (EasyPermissions.isGranted(this, listP)) {
            initPic()
//            dispatchTakePictureIntent()
        } else {
            PermissionLauncher().with(this)
                .granted {
                    //所有权限都被授予了回调此处
                    initPic()
//                    dispatchTakePictureIntent()
                }
                .denied {
                    //有权限被拒绝回调此处
                    //rejectPermissionList为被拒绝的权限列表
                    DialogHelper.showPermissionHintDialog(this@RechargeActivity, "相机和存储服务未开启", "请在设置中为本应用开启相机和存储服务以正常使用功能") {
                        PermissionLauncher.openAppDetailSettings(this@RechargeActivity)
                    }
                }
                .request(
                    arrayOf(Permission.CAMERA),
                    arrayOf(getString(R.string.okpermission_camera)),
                    arrayOf(getString(R.string.okpermission_camera_rationale))
                )
        }
    }

    private fun initPic() {
        PictureSelector.create(this)
            .openGallery(SelectMimeType.ofImage())
            .setImageEngine(GlideEngine.createGlideEngine())
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>?) {
                    result?.let { it ->
                        val path = it[0]?.realPath
                        path?.let {
                            val str = FileUtils.compressImageAndGetBase64String(path)
                            if (TextUtils.isEmpty(str)) {
                                showToast("图片压缩失败")
                                return@let
                            }
                            showLoading("识别中...")
                            viewModel.getOcrInfo(str!!)
                        }
                    }
                }

                override fun onCancel() {}
            })
    }

    override fun initData() {
        binding.rechargeHead.statusBarView.layoutParams.height = CommonUtils.getStatusBarHeight()
        var filters = arrayOf<InputFilter>(CashierInputFilter())
        binding.etBalance.filters = filters

        binding.rvOther.layoutManager = LinearLayoutManager(this)
        binding.rvOther.addItemDecoration(SpacesItemDecoration(AppUtils.dip2px(10f)))
        rechargeAdapter = RechargeAdapter(object : OnItemClickListener {
            override fun onItemClick(channel: ChannelList) {
                channelList = channel
                selectResult = channel.payType
                visibleOther()
            }
        })
        binding.rvOther.adapter = rechargeAdapter
        showLoading()
        viewModel.getMyInfo()
        viewModel.getChannelList()
    }

    override fun initBinding(): ActivityRechargeBinding {
        return ActivityRechargeBinding.inflate(layoutInflater)
    }

    private fun getAilPay(payData: String) {
        // 完整的符合支付宝参数规范的订单信息
        val payRunnable = Runnable { // 构造PayTask 对象
            val alipay = PayTask(this@RechargeActivity)
            // 调用支付接口，获取支付结果
            val result = alipay.pay(payData, true)

            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            handle.sendMessage(msg)
        }
        // 必须异步调用
        Thread(payRunnable).start()
    }

    @SuppressLint("HandlerLeak")
    private val handle = Handler { msg ->
        when (msg.what) {
            SDK_PAY_FLAG -> {
                if (msg.obj is Map<*, *>) {
                    @SuppressWarnings("unchecked")
                    val payResult = PayResult(msg.obj as Map<String, String>)

                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo = payResult.result // 同步返回需要验证的信息
                    val resultStatus = payResult.resultStatus
                    // resultStatus={9000};memo={};result={{"alipay_trade_app_pay_response":{"code":"10000","msg":"Success","app_id":"2021004199650878","auth_app_id":"2021004199650878","charset":"UTF-8","timestamp":"2024-12-04 10:09:46","out_trade_no":"1_1864129913250983937","total_amount":"0.01","trade_no":"2024120422001401751415025114","seller_id":"2088641231292273"},"sign":"enc1DhlFAGR9C43bASvPocDTLthkJ/flAZU0nxbmMnesNkA+H0d6Ek60b8NbVzVqU+RbBOqWbpDqXHgmXDs27aBvQP0iiiEduC44QzEi6YWi2WoMBJSkttyEky8aPaYUxJbKbi2GcbIAQ7Q7Vogvj8qPpiXpxl4Ht7TocV+EjnOqoZhldypdBnTSr3uovgM5+dgy8OOvqbDP/gFXkAeY1Nh3++bi24/vWYVHC7nidN5G7RzzPX6rOH5jEEoK8dhFsrown8vEr/gbE/sHOqXk7uRy8F6SWt1qgQ0emaQqT7n87BiX7d6D4QRhRpHjCaRCajuNc6T3BhlrWPpFSKpVBw==","sign_type":"RSA2"}};extendInfo={{"doNotExit":true,"isDisplayResult":true,"tradeNo":"2024120422001401751415025114"}}
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        showToast("支付成功")
                        binding.etBalance.setText("")
                        showLoading()
                        viewModel.getMyInfo()
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        showLoading()
                        viewModel.getMyInfo()
                    }
                } else {
                    // 解析
                    var sp = msg.obj.toString().split(";")
                    if (sp.size > 1) {
                        var status = sp[0].substring(sp[0].indexOf("{") + 1, sp[0].lastIndexOf("}"))
                        if (TextUtils.equals(status, "9000")) {
                            binding.etBalance.setText("")
                            showToast("充值成功")
                            balanceChange = true
                        }
                    }
                    showLoading()
                    viewModel.getMyInfo()
                }
            }
        }
        false
    }

    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
        if (TextUtils.isEmpty(selectResult)) {
            if (balanceChange) {
                setResult(RESULT_OK, Intent().putExtra("balance", binding.rechargeHead.tvQbye.text.toString()))
            }
            finish()
        } else {
            visibleSelect()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 20 && resultCode == RESULT_OK) {
            val str = FileUtils.compressImageAndGetBase64String(filePath!!.absolutePath)
            if (TextUtils.isEmpty(str)) {
                showToast("图片压缩失败")
                return
            }
            showLoading("识别中...")
            viewModel.getOcrInfo(str!!)
        } else {
            if (data == null) {
                return
            }
            var msg = ""
            val str = data.extras?.getString("pay_result")
            if (TextUtils.equals(str, "success")) {
                msg = "充值成功！"
                binding.etBalance.setText("")
            } else if (TextUtils.equals(str, "fail")) {
                msg = "支付失败！"
            } else if (TextUtils.equals(str, "cancel")) {
                msg = "用户取消了支付"
            }
            showToast(msg)
        }
    }

    private fun confirmPay(trim: String) {
        openPayActivity(this, trim,
            object : OrderResultCallBack {
                override fun onSuccess(payResultVO: PayResultVO) {
                    PayActivity.finishPayActivity()
                    showToast("支付成功")
                    showLoading()
                    viewModel.getMyInfo()
                }

                override fun onError(payResultVO: PayResultVO) {
                    PayActivity.finishPayActivity()
                    showLoading()
                    viewModel.getMyInfo()
                }
            })
    }
}